<?php

namespace app\admin\service;
use app\admin\model\User;
use think\facade\Db;

class UserService
{   
    public function getUserList($param)
    {   
        $query = User::withOutField('password');

        if(!empty($param['keyword'])){
            $where1 = [
                ['phone','=',$param['keyword']]  
            ];

            $where2 = [
                ['nickname','=',$param['keyword']]
            ];

            $query->whereOr([$where1,$where2]);
        }

        $users = $query->paginate(10);
        return $users;
    }

    public function findUser($id)
    {   
        $model = new User();
        $User = $model->withOutField('password,create_time,update_time')->find($id);

        return $User;
    }

    public function getRoleOption($User_id = false)
    {   
        $roles = Db::name('role')->field('id,name')->where('store_id',0)->select();

        if(!$User_id){
            return $roles;
        }

        $ids =  Db::name('User_role')->field('role_id')->where('User_id',$User_id)->select();
        
        $roleArr = $roles->isEmpty() ? [] : $roles->toArray();
        $idArr = $ids->isEmpty() ? [] : array_column($ids->toArray(),'role_id');
        
        $options = [];
        foreach($roleArr as $k => $v){
            in_array($v['id'],$idArr) ? $v['checked'] = 1 : $v['checked'] = 0;
            $options[$k] = $v;
        }

        return $options;
    }
    
    public function saveUser($data)
    {   
        
       
        $model = User::create($data);
        $arr = [];

        foreach($data['roles'] as $k => $v){
            $arr[$k]['User_id'] = $model['id'];
            $arr[$k]['role_id'] = $v;
        }

        $rows = Db::name('User_role')->insertAll($arr);

        return  $model['id'] && $rows;
    }

    public function updateUser($data)
    {
        $model = new User();
        
        if(empty($data['password'])){
            unset($data['password']);
        }
        
        $model->update($data);

        foreach($data['roles'] as $k => $v){
            $arr[$k]['User_id'] = $data['id'];
            $arr[$k]['role_id'] = $v;
        }
        Db::name('User_role')->where('User_id',$data['id'])->delete();
        Db::name('User_role')->insertAll($arr);
        return $model;
    }


    public function changeUser($data)
    {
        
        if(empty($data['password'])){
            unset($data['password']);
        }
        
        $model = User::update($data);

        session('avatar',$model['avatar']);
        session('nickname',$model['nickname']);
       

        return $model;
    }


    public function deleteUser($id)
    {   
        $model = new User();
        $res =$model->where('id',$id)->delete();
       
        return $res ? true : false;
    }
}